package com.fangda.network;

import io.vertx.core.Vertx;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 网络组件管理，利用单例模式实现，在集群环境中无法运行
 * @author 赵方方
 */
public class NetworkManager {

    private static final NetworkManager INSTANCE = new NetworkManager();

    private final Map<String, Network> store = new ConcurrentHashMap<>();

    public static NetworkManager getInstance() {
        return INSTANCE;
    }

    private final Vertx vertx;

    private NetworkManager() {
        vertx = Vertx.vertx();
    }

    public Network createNetwork(String id, NetworkProvider<? extends Network> provider, NetworkConfig networkConfig, NetworkCallback callback) {
        Network network = store.get(id);
        if(network == null) {
            network = provider.createNetwork(vertx, id, networkConfig);
            store.put(id, network);
        }
        if(callback != null) {
            network.setCallback(callback);
        }
        return network;
    }


    public Network createNetwork(NetworkProvider<? extends Network> provider, NetworkConfig networkConfig, NetworkCallback callback) {
        return this.createNetwork(UUID.randomUUID().toString(), provider, networkConfig, callback);
    }

    public Network createNetwork(String id, String ip, Integer port, String path,
                                 NetworkProvider<? extends Network> provider,  NetworkCallback callback, NetWorkParser<?> netWorkParser) {
        NetworkConfig config = new NetworkConfig();
        config.setIp(ip);
        config.setPort(port);
        config.setParser(netWorkParser);
        if(path != null) {
            if(!path.startsWith("/")) {
                path = "/" + path;
            }
            config.setPath(path);
        } else {
            config.setPath("/");
        }
        return createNetwork(id, provider, config, callback);
    }

    public Network createNetwork(String ip, Integer port, String path, NetworkProvider<? extends Network> provider,
                                 NetworkCallback callback, NetWorkParser<?> netWorkParser) {
       return createNetwork(UUID.randomUUID().toString(), ip, port, path, provider, callback, netWorkParser);
    }

    public Network getNetwork(String id) {
        return store.get(id);
    }
}
